
import { RoleAttributeType, RoleModuleType } from "../RoleEnum";
import { RoleNumeric } from "./RoleNumeric";
import { RoleNumericCls } from "./RoleNumericCls";
import { RoleNumericDecorator } from "./RoleNumericDecorator";

/** 所有模块角色属性集合 */
export class RoleNumericMap {
    /** 角色属性 */
    private attributes: Map<RoleAttributeType, RoleNumeric> = new Map();
    /** 角色属性修饰器 */
    private decorators: Map<RoleNumericDecorator, number> = new Map();
    /** MVVM组件数据 */
    private vm: any = {};

    constructor(vm: any) {
        this.vm = vm;
    }

    /** 添加属性修饰器 */
    addDecorator(type: RoleAttributeType | RoleNumericDecorator, value?: number): RoleNumericDecorator {
        var rnd: RoleNumericDecorator = null!;
        if (type instanceof RoleNumericDecorator)
            rnd = type;
        else
            rnd = new RoleNumericDecorator(type, value!);

        this.decorators.set(rnd, rnd.value);
        var rn = this.get(rnd.attribute);
        var decorator = rn.getValue(RoleModuleType.Decorator)!;
        rn.setValue(RoleModuleType.Decorator, rnd.value + decorator);

        return rnd
    }

    /** 移除属性修饰器 */
    removeDecorator(rnd: RoleNumericDecorator) {
        this.decorators.delete(rnd);
        var rn = this.get(rnd.attribute);
        var decorator = rn.getValue(RoleModuleType.Decorator)!;
        rn.setValue(RoleModuleType.Decorator, decorator - rnd.value);
    }

    /** 移除所有属性修饰器 */
    removeAllDecorator() {
        this.decorators.forEach((element, rnd) => {
            var rn = this.get(rnd.attribute);
            var decorator = rn.getValue(RoleModuleType.Decorator)!;
            rn.setValue(RoleModuleType.Decorator, decorator - rnd.value);
        });
        this.decorators.clear();
    }

    /** 获取角色属性 */
    get(type: RoleAttributeType): RoleNumeric {
        var attr = this.attributes.get(type)!;
        if (attr == null) {
            var cls = RoleNumericCls[type];
            if (cls) {
                attr = new cls(type, this);
            }
            else {
                attr = new RoleNumeric(type, this);
            }
            this.attributes.set(type, attr);

            attr.onUpdate = (rn: RoleNumeric) => {
                this.vm[rn.type] = rn.value;
            };
        }
        return attr;
    }

    forEach(callbackfn: (value: RoleNumeric, key: RoleAttributeType, map: Map<RoleAttributeType, RoleNumeric>) => void, thisArg?: any): void {
        this.attributes.forEach(callbackfn, thisArg);
    }

    /** 重置属性值为零 */
    reset() {
        // 清理修饰器中的值
        this.decorators.clear();

        // 清理属性值
        this.attributes.forEach((value: RoleNumeric, key: RoleAttributeType, map: Map<RoleAttributeType, RoleNumeric>) => {
            value.reset();
        });
    }
}